<?php
namespace com\rs\dns\filter;

use com\rs\dns\constant\ApiConstant;
use com\rs\dns\constant\ConfigConstant;
use com\rs\dns\constant\UserSessionErrorConstant;
use com\rs\dns\controller\api\vo\DomainForm;
use com\rs\dns\exception\BaException;
use com\rs\dns\service\ConfigService;
use com\rs\dns\service\DomainService;
use com\rs\dns\service\user\impl\UserServiceImpl;
use com\rs\dns\service\user\impl\UserSessionServiceImpl;
use restphp\http\RestHttpRequest;
use restphp\utils\RestClassUtils;
use restphp\utils\RestSplitterUtils;
use restphp\utils\RestStringUtils;

/**
 * Class ApiFilter
 * @package com\rs\sn\filter
 */
final class ApiFilter {
    /**
     * 接口授权api.
     * @throws \restphp\exception\RestException
     */
    public static function run() {


        //获取账号
        $authorize = RestHttpRequest::getHttpHeader("authorize");
        if (RestStringUtils::isBlank($authorize)) {
            //如果不是api访问，跳出.
            return;
        }
        $arrAuth = RestSplitterUtils::on(';')->withKeyValueSeparator('=')->split($authorize);
        if (!isset($arrAuth['user']) || RestStringUtils::isBlank($arrAuth['user']) ||
            !isset($arrAuth['pwd']) || RestStringUtils::isBlank($arrAuth['pwd'])) {
            throw new BaException(ApiConstant::HTTP_API_ACCOUNT_ERROR);
        }

        //检查接口是否开启
        if (!self::isOpen()) {
            throw new BaException(ApiConstant::HTTP_API_CLOSED);
        }

        //获取账号
        $userService = new UserServiceImpl();
        $user = $userService->getInfoByUsername($arrAuth['user']);
        if (null == $user) {
            self::autoCreate($arrAuth['user'], $arrAuth['pwd']);
            $user = $userService->getInfoByUsername($arrAuth['user']);
        }
        if (null == $user) {
            throw new BaException(ApiConstant::HTTP_API_ACCOUNT_ERROR);
        }
        if ($user->getPassword() != $arrAuth['pwd']) {
            throw new BaException(ApiConstant::HTTP_API_ACCOUNT_ERROR);
        }
        if ("N" == $user->getVerify()) {
            throw new BaException(UserSessionErrorConstant::USER_LOGIN_ERROR_NOT_ALLOWED);
        }
        if ("R" == $user->getVerify()) {
            throw new BaException(UserSessionErrorConstant::USER_LOGIN_ERROR_NOT_PASS);
        }
        if ("S" == $user->getVerify()) {
            throw new BaException(UserSessionErrorConstant::USER_LOGIN_ERROR_ACCOUNT_STOPPED);
        }

        //设置登录状态
        $userSessionService = new UserSessionServiceImpl();
        $userSessionService->makeSession($user);
    }

    /**
     * 是否开启API.
     * @return bool
     * @throws \restphp\exception\RestException
     */
    private static function isOpen() {
        $allow = ConfigService::getConfigValue(ConfigConstant::CODE_ALLOW_HTTP_API);
        return "Y" == $allow;
    }

    /**
     * 是否为服务级调用.
     * @return bool
     * @throws \restphp\exception\RestException
     */
    private static function isServer() {
        $serverAuthorize = RestHttpRequest::getHttpHeader("server-authorize");
        $serverKey = ConfigService::getConfigValue(ConfigConstant::CODE_SERVER_KEY);
        return $serverAuthorize == $serverKey;
    }

    /**
     * 自动创建用户.
     * @param $username
     * @param $pwd
     * @throws BaException
     * @throws \restphp\exception\RestException
     */
    private static function autoCreate($username, $pwd) {
        if (!self::isServer()) {
            throw new BaException(ApiConstant::HTTP_API_ACCOUNT_ERROR);
        }
        $autoCreate = RestHttpRequest::getHttpHeader("server-auto-create");
        if ("Y" != strtoupper($autoCreate)) {
            throw new BaException(ApiConstant::HTTP_API_ACCOUNT_ERROR);
        }
        $userService = new UserServiceImpl();
        $userService->apiCreate($username, $pwd);
    }

    /**
     * 自动添加域名.
     * @param $username
     * @param $domain
     * @throws BaException
     * @throws \restphp\exception\RestException
     */
    public static function autoCreateDomain($username, $domain) {
        if (!self::isServer()) {
            return;
        }

        $autoCreate = RestHttpRequest::getHttpHeader("server-domain-auto-create-limit");
        if (RestStringUtils::isBlank($autoCreate)) {
            return;
        }
        $limitTime = date('Y-m-d H:i:s', strtotime($autoCreate));
        if (RestStringUtils::isBlank($limitTime)) {
            return;
        }

        $domainForm = new DomainForm();
        $domainForm->setUsername($username);
        $domainForm->setOrigin($domain);
        $domainForm->setTopdate(date('Y-m-d H:i:s'));
        $domainForm->setEnddate($limitTime);
        $domainForm->setYn(1);

        DomainService::add($domainForm);
    }
}